package cn.swenty.backstage.framework.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.swenty.backstage.framework.common.FormMap;
import cn.swenty.backstage.framework.common.Global;
import cn.swenty.backstage.framework.common.model.User;
import cn.swenty.backstage.framework.database.entity.Entity;
import cn.swenty.backstage.framework.database.plugin.PageView;
import cn.swenty.backstage.framework.util.Common;

public abstract class BasicController {
	
	protected String webRoot = Common.BACKGROUND_PATH;


	@RequestMapping("{page}")
	public String page(@PathVariable("page") String page) {
		return this.getBaseQuestMapping(page);
	}

	/**
	 * 获取主路径
	 * 
	 * @return
	 */
	public String getBaseQuestMapping() {

		RequestMapping rm = this.getClass().getAnnotation(RequestMapping.class);
		if (rm == null || rm.value() == null || rm.value().length == 0) {
			return "";
		} else {
			return webRoot + rm.value()[0];
		}
	}

	/**
	 * 获取主路径
	 * 
	 * @return
	 */
	public String getBaseQuestMapping(String page) {

		RequestMapping rm = this.getClass().getAnnotation(RequestMapping.class);
		if (rm == null || rm.value() == null || rm.value().length == 0) {
			return page;
		} else {
			return webRoot + rm.value()[0] + page;
		}
	}

	public PageView pageView = null;

	/**
	 * 转pageview
	 * 
	 * @return
	 */
	protected PageView getPageView() {
		String pageNow = getPara("page");
		String pageSize = getPara("limit");
		String orderby = getPara("sort");
		if (Common.isNotEmpty(pageNow) && Common.isNotEmpty(pageSize)) {
			pageView = new PageView(Integer.parseInt(pageSize),Integer.parseInt(pageNow));
		} 
		if (orderby != null && !orderby.equals("")) {
			String[] sortArr = orderby.split(",");
			orderby = " order by " + sortArr[0];
			if (sortArr.length == 2) {
				orderby = orderby + " " + sortArr[1] + " ";
			}
			pageView.setOrderby(orderby);
		}
		
		return pageView;
	}

	protected <T> T toPageEntity(T t) {
		FormMap formMap = (FormMap) t;
		formMap.put(Entity.PAGE_VIEW, getPageView());
		return t;
	}

	protected <T extends Entity> T getPageEntity(Class<T> t) {
		T formMap = this.getEntity(t);
		formMap.put(Entity.PAGE_VIEW, getPageView());
		return formMap;
	}

	public Map<String, Object> toPage(List<? extends Entity> objs) {
		Map<String, Object> map = new HashMap<>();
		map.put("code", 0);
		if(pageView != null){
			map.put("count", pageView.getRowCount());
		}
		map.put("data", objs);
		map.put("msg", "");
		return map;
	}

	/**
	 * 获取request对象 <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspsunyang</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b>
	 */
	public HttpServletRequest getHttpRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public void setRequestAttribute(String key, Object obj) {
		this.getHttpRequest().setAttribute(key, obj);
	}

	/**
	 * 获取response对象 <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspsunyang</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b>
	 */
	public HttpServletResponse getHttpResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	}

	/**
	 * 获取页面传递的某一个参数值, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b>
	 */
	public String getPara(String key) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request.getParameter(key);
	}

	/**
	 * 获取传递的所有参数, 反射实例化对象，再设置属性值 通过泛型回传对象. <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b>
	 * 
	 * @return Class<T>
	 * @throws Exception
	 */
	public <T extends Entity> T getEntity(Class<T> clazz) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		Enumeration<String> en = request.getParameterNames();
		T t = null;
		try {
			t = clazz.newInstance();
			while (en.hasMoreElements()) {
				String nms = en.nextElement().toString();
				if (nms.endsWith("[]")) {
					String[] as = request.getParameterValues(nms);
					if (as != null && as.length != 0 && as.toString() != "[]") {
						String mname = t.getClass().getSimpleName().toUpperCase();
						if (nms.toUpperCase().startsWith(mname)) {
							nms = nms.substring(nms.toUpperCase().indexOf(mname) + 1);
							t.put(nms, as);
						}
					}
				} else {
					String as = request.getParameter(nms);
					if (!Common.isEmpty(as)) {
						String mname = t.getClass().getSimpleName().toUpperCase();
						if (nms.toUpperCase().startsWith(mname)) {
							nms = nms.substring(mname.length() + 1);
							t.put(nms, as);
						}
					} else {
						String mname = t.getClass().getSimpleName().toUpperCase();
						if (nms.toUpperCase().startsWith(mname)) {
							nms = nms.substring(mname.length() + 1);
							// t.put(nms, null);
						}
					}
				}
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * 获取页面传递的某一个数组值, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b>
	 * 
	 * @return Class<T>
	 * @throws Exception
	 */
	public String[] getParaValues(String key) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		if (key.endsWith("[]")) {
			return request.getParameterValues(key);
		} else {
			if (request.getParameterValues(key) == null) {
				return request.getParameterValues(key + "[]");
			}
		}

		return request.getParameterValues(key);
	}

	/**
	 * 获取传递的所有参数, 再设置属性值 通过回传Map对象. <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplijianning</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp1.0v</b>
	 * 
	 * @return Class<T>
	 * @throws Exception
	 */
	public <T extends FormMap> T findHasHMap(Class<T> clazz) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		Enumeration<String> en = request.getParameterNames();
		T map = null;
		try {
			map = clazz.newInstance();
			while (en.hasMoreElements()) {
				String nms = en.nextElement().toString();
				if (!"_t".equals(nms)) {
					if (nms.endsWith("[]")) {
						String[] as = request.getParameterValues(nms);
						if (as != null && as.length != 0 && as.toString() != "[]") {
							map.put(nms, as);
						}
					} else {
						String as = request.getParameter(nms);
						if (!Common.isEmpty(as)) {
							map.put(nms, as);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	protected HttpSession getHttpSession() {

		return getHttpRequest().getSession();

	}

	protected Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	protected User getUser() {
		return Global.getCurrentUser();
	}

}
